#include "bodywrapper.h"
#include "forcewrapper.h"
#include <QPainter>

bool BodyWrapper::pointInRegion(b2Vec2 point, int top, int left, int right, int bottom)
{
    return point.x >= left && point.x <= right && point.y >= top && point.y <= bottom;
}

int BodyWrapper::applyForce(ForceWrapper *force)
{
    forces[curr_force_id] = force->clone();
    return curr_force_id ++;
}

void BodyWrapper::removeForce(int forceId)
{
    auto forceIter = forces.find(forceId);
    ForceWrapper *force = forceIter->second;
    if(forceIter != forces.end()) {
        forces.erase(forceIter);
    }
    delete force;
}

void BodyWrapper::applyImpulse(b2Vec2 impulse)
{
    body->ApplyLinearImpulse(impulse, impulse, true);
}

void BodyWrapper::step()
{
    for(auto iter = forces.begin(); iter != forces.end(); ++ iter) {
        iter->second->step();
        body->ApplyForceToCenter(iter->second->getForce(), true);
    }
}

void BodyWrapper::draw(QPainter *painter)
{
    painter->save();
    QPen pen(Qt::darkMagenta, 3.0/20);
    painter->setPen(pen);
    b2Vec2 point = getPosition();
    QPointF pos(point.x, point.y);
    painter->drawPoint(QPointF(pos));
    painter->restore();
}

BodyWrapper::~BodyWrapper()
{
    for(auto iter = forces.begin(); iter != forces.end(); ++ iter) {
        delete iter->second;
    }
    world->DestroyBody(body);
}
